/*
 * @Author: 陈永浩(cyh1231wp@163.com)
 * @Date: 2020-12-18 14:51:57
 * @LastEditors: 陈永浩(cyh1231wp@163.com)
 * @LastEditTime: 2021-02-22 21:45:27
 */
import router from '@/router'
import store from '@/store'
import { tokenName } from '@/config'
import Vue from 'vue'
import { login, logout } from '../../api/system/login'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from '@/utils/accessToken'

const state = () => ({
  accessToken: getAccessToken(),
  username: '',
  avatar: '',
  permissions: [],
})
const getters = {
  accessToken: (state) => state.accessToken,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  permissions: (state) => state.permissions,
}
const mutations = {
  setAccessToken(state, accessToken) {
    state.accessToken = accessToken
    setAccessToken(accessToken)
  },
  setUsername(state, username) {
    state.username = username
  },
  setAvatar(state, avatar) {
    state.avatar = avatar
  },
  setPermissions(state, permissions) {
    state.permissions = permissions
  },
}
const actions = {
  setPermissions({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    console.log(res);
    if (res.code != 0) {
      Vue.prototype.$baseMessage(res.msg, 'error')
      throw new Error(res.msg)
    }
    sessionStorage.setItem('adminInfo', JSON.stringify(res.data));
    const accessToken = res.data[tokenName];
    if (accessToken) {

      commit('setAccessToken', accessToken);

      // let accessRoutes = await store.dispatch('routes/setAllRoutes')
      // console.log(accessRoutes);
      // router.addRoutes(accessRoutes);

    } else {
      Vue.prototype.$baseMessage(
        `登录接口异常，未正确返回${tokenName}...`,
        'error'
      )
      throw new Error(`登录接口异常，未正确返回${tokenName}...`)
    }
  },
  async getUserInfo({ commit, state }) {

  },
  async logout({ dispatch }) {
    await logout(state.accessToken)
    await dispatch('resetAccessToken')
  },
  resetAccessToken({ commit }) {
    commit('setPermissions', [])
    commit('setAccessToken', '')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
